from flask import Blueprint, render_template, request, g
from flask_login import login_required
from inc.models import OperationLog, AdminUser

from sqlalchemy import desc, or_

import pytz

admin_log_bp = Blueprint('admin_log', __name__)

@admin_log_bp.route('/operation-logs')
@login_required

def operation_logs():
    page = request.args.get('page', 1, type=int)
    per_page = 20
    search = request.args.get('search', '')
    admin_id = request.args.get('admin_id', type=int)
    action = request.args.get('action', '')
    resource = request.args.get('resource', '')
    query = OperationLog.query
    if search:
        query = query.filter(or_(
            OperationLog.details.ilike(f'%{search}%'),
            OperationLog.ip_address.ilike(f'%{search}%')
        ))
    if admin_id:
        query = query.filter(OperationLog.admin_id == admin_id)
    if action:
        query = query.filter(OperationLog.action.ilike(f'%{action}%'))
    if resource:
        query = query.filter(OperationLog.resource == resource)
    logs = query.order_by(desc(OperationLog.timestamp)).paginate(page=page, per_page=per_page)
    # 预处理时间格式
    for log in logs.items:
        log.formatted_time = log.timestamp.replace(tzinfo=pytz.UTC).astimezone(
            pytz.timezone(g.system_config.timezone if hasattr(g, 'system_config') else 'Asia/Shanghai')
        ).strftime('%Y-%m-%d %H:%M')
    admins = AdminUser.query.all()
    return render_template('admin/admin/admin_logs.html', logs=logs, admins=admins)